package cn.bytecollege.admin.controller; /**
 * @Auther：MR.P
 * @Date:2021/10/29 09 03
 * @Description:根据分类Id删除分类，如果该分类下存在商品则不允许删除
 */

import cn.bytecollege.admin.service.ClassifyService;
import cn.bytecollege.admin.service.ProductService;
import cn.bytecollege.common.entity.Product;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ClassifyDeleteController", value = "/admin/classifyDelete")
public class ClassifyDeleteController extends HttpServlet {
    private ClassifyService  classifyService = null;
    private ProductService productService = null;
    public ClassifyDeleteController(){
        classifyService = new ClassifyService();
        productService = new ProductService();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = null;
        String id = request.getParameter("classifyId");
        Integer classifyId = Integer.valueOf(id);
        //根据分类id查询商品
        List<Product> list = productService.findProductByClassifyId(classifyId);
        if(list.size() > 0){
            msg = "该分类下存在商品，请先删除商品，再删除分类";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(request.getContextPath()+"/admin/classifyList").forward(request,response);
            return;
        }
        //代码能执行到这里说明该分类没有被引用或者说该分类下没有商品，可以直接删除
        classifyService.deleteClassifyById(classifyId);
        //重定向防止重复删除
        response.sendRedirect(request.getContextPath()+"/admin/classifyList");
    }
}
